﻿using System;
using System.Collections.Generic;
using System.Linq;
using DAL;

namespace Administratation.Classes
{
    class DatabasePersister
    {
        public static IEnumerable<Country> GetCountries()
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            return context.Countries.Include("Towns");
        }

        public static void SaveCountry(Country country)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            Country result = context.Countries.FirstOrDefault(c => c.CountryID == country.CountryID);
            if (result == null)
            {
                throw new NullReferenceException("No such country");
            }
            else
            {
                result.Name = country.Name;
            }
            context.SaveChanges();
        }

        public static void AddCountry(Country country)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            context.Countries.AddObject(country);
            context.SaveChanges();
        }

        public static void DeleteCountry(Country country)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            Country result = context.Countries.FirstOrDefault(c => c.CountryID == country.CountryID);
            
            if (result != null)
            {
                if (result.Towns.Count > 0)
                {
                    throw new Exception("Can't delete Country with town in it.");
                }
                else
                {
                    context.Countries.DeleteObject(result);
                    context.SaveChanges();
                }
            }
        }

        internal static IEnumerable<Town> GetTowns()
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            return context.Towns.ToList<Town>();
        }

        internal static void AddTown(Town town)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            context.Towns.AddObject(town);
            context.SaveChanges();
        }

        internal static IEnumerable<Town> GetTownsByCountryID(int countryID)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            IEnumerable<Town> towns = context.Towns.Where(t => t.CountryID == countryID).ToList<Town>();
            return towns;
        }

        internal static void DeleteTown(Town town)
        {
            WPF_ExamEntities context = new WPF_ExamEntities();
            Town result = context.Towns.FirstOrDefault(t => t.TownID == town.TownID);
            if (result != null)
            {
                context.Towns.DeleteObject(result);
                context.SaveChanges();
            }
        }
    }
}
